package com.zcxx.controller;

import com.zcxx.common.Result;
import com.zcxx.model.SysUser;
import com.zcxx.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sysUser")
@Api(tags = "系统用户管理", description = "管理系统用户的增删改查操作")
public class SysUserApiController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping
    @ApiOperation(value = "获取所有用户", notes = "查询所有用户信息，返回用户列表")
    public Result<List<SysUser>> getAllUsers() {
        List<SysUser> users = sysUserService.list();
        return Result.success(users);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID获取用户", notes = "根据用户ID查询用户信息，返回用户详情")
    public Result<SysUser> getUserById(
            @ApiParam(name = "id", value = "用户ID", required = true) @PathVariable Long id
    ) {
        SysUser user = sysUserService.getById(id);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.error("用户不存在");
        }
    }

    @PostMapping
    @ApiOperation(value = "添加用户", notes = "创建一个新用户，返回创建的用户信息")
    public Result<SysUser> addUser(@RequestBody SysUser user) {
        boolean saved = sysUserService.save(user);
        if (saved) {
            return Result.success(user);
        } else {
            return Result.error("添加用户失败");
        }
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "更新用户", notes = "根据用户ID更新用户信息，返回更新后的用户信息")
    public Result<SysUser> updateUser(
            @ApiParam(name = "id", value = "用户ID", required = true) @PathVariable Long id,
            @RequestBody SysUser user
    ) {
        user.setUserId(id);
        boolean updated = sysUserService.updateById(user);
        if (updated) {
            return Result.success(user);
        } else {
            return Result.error("更新用户失败");
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户", notes = "根据用户ID删除用户")
    public Result<Void> deleteUser(
            @ApiParam(name = "id", value = "用户ID", required = true) @PathVariable Long id
    ) {
        boolean deleted = sysUserService.removeById(id);
        if (deleted) {
            return Result.success(null);
        } else {
            return Result.error("删除用户失败");
        }
    }
}